package com.pxml2pdf.pdf.Node;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import com.itextpdf.text.BadElementException;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.ColumnText;
import com.itextpdf.text.pdf.PdfContentByte;

public class TextNode extends BaseNode {

	private static final String COMBO = "combo";
	private static final float COMBO_EXP = 3.5f;
	private static final float TEXT_EXP_Y = 2f;
	private static final float TEXT_EXP_X = 2f;
	private static final float TEXT_OFF_Y = -3f;
	private static final float ICON_OFF = 2F;
	private static final String ICON_NAME = "combo_select.gif";
	private static final float ROUND_VAL = 2f;
	
	
	private  float x_ex=0f;
	private  float Y_EX=4f;

	// private static final String ICON_NAME="arrow-dn.gif";

	@Override
	public void drawingBox(PdfContentByte cb) {
		float image_y_ex=0f;
		if (getValue().length()>25 &&((getWidth()* getScale())<400)){
			x_ex =70f;
			if ((getUrx()+x_ex)>580f){
				x_ex=580f-getUrx();
			}
			if(getValue().length()>40){
				expansion_Y(Y_EX);
				image_y_ex=Y_EX;
			}
			
			
		}	
		float hei = getHeight() * getScale();
		if (getClasses().indexOf(COMBO) >= 0) {
			// System.out.println(getPnode().getClasses());
			expansion_X(COMBO_EXP);
			off_Y(TEXT_OFF_Y);
			URL filename = getIcons(ICON_NAME);
			try {
				Image image = Image.getInstance(filename);
				image.setAbsolutePosition(getUrx() + ICON_OFF+x_ex, getLly()+image_y_ex);
				image.setAlignment(Image.UNDERLYING);
				image.scaleAbsolute(hei - ICON_OFF, hei);
				cb.addImage(image);
			} catch (BadElementException e) {
				e.printStackTrace();
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (DocumentException e) {
				e.printStackTrace();
			}
			setUrx(getUrx() + hei);
		}
		cb.setLineWidth(LINE_WIDTH);
		cb.setColorStroke(LINE_COLOR);
		cb.roundRectangle(getLlx()-TEXT_EXP_X, getLly()-TEXT_EXP_Y, getUrx()+x_ex - getLlx()+TEXT_EXP_X, getUry() - getLly()+2*TEXT_EXP_Y, ROUND_VAL);

		// cb.moveTo(getLlx(), getLly());
		// cb.lineTo(getLlx(), getUry());
		// cb.lineTo(getUrx(), getUry());
		// cb.lineTo(getUrx(), getLly());
		// cb.lineTo(getLlx(), getLly());
		cb.stroke();
	}

	@Override
	protected void fillValue(PdfContentByte cb, Font font) throws DocumentException {
		Phrase phrase = new Phrase(getValue(), font);
		ColumnText ct = new ColumnText(cb);
		ct.setSimpleColumn(phrase, getLlx(), getLly(), getUrx()+x_ex, getUry(), LEADING, getAlign());
		// System.out.println(getValue() + "   x=" + getLlx() + " y=" +
		// getLly());
		ct.go();
	}

}
